package com.jstyle.beatecg.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;

import com.jstyle.beatecg.R;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.PdfUtils;
import com.jstyle.beatecg.util.SchedulersTransformer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class HeartHistoryShareActivity extends AppCompatActivity {
    @BindView(R.id.heaart_share) ImageView heaart_share;//分享
    @BindView(R.id.heaart_bck) ImageView back;//返回
    @BindView(R.id.history_webview) WebView webView;//显示的图表
    String filepath;
    private List<Integer> data=new ArrayList<>();
    private Disposable disposablePdf;

     String pathPdf;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_historyshare);
        ButterKnife.bind(this);
        filepath=getIntent().getStringExtra("filePath");
        data=Fileread(filepath);
        WebviewSetting();
        createFile();

    }

    /**
     * WebviewSetting
     *
     */

    @SuppressLint("SetJavaScriptEnabled")
    private  void WebviewSetting(){
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setSupportZoom(true);//缩放开关，设置此属性，仅支持双击缩放，不支持触摸缩放
        webSettings.setBuiltInZoomControls(true); //设置是否可缩放，会出现缩放工具（若为true则上面的设值也默认为true）
        webSettings.setUseWideViewPort(true); //扩大比例的缩放
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setDisplayZoomControls(false); //隐藏缩放工具
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式


        webView.setInitialScale(20);//为25%，最小缩放等级

        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // 设置无边框
        // 支持内容重新布局
         //webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        webSettings.supportMultipleWindows();
        webSettings.setSupportMultipleWindows(true);

    }



    @OnClick({R.id.heaart_bck, R.id.heaart_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.heaart_bck:
                finish();
                break;
            case  R.id.heaart_share:
                if(!TextUtils.isEmpty(pathPdf)){
                    sharePdfByPhone(HeartHistoryShareActivity.this, pathPdf);
                }
                break;

        }}
    private void createFile() {
        File dir = new File(ImageUtils.pdfPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //得到egg文件名字，默认为时间戳
        String dateS=filepath.replace(ImageUtils.ecgPath,"");
        final String date= dateS.substring(0,dateS.length()-4).trim();
        pathPdf = ImageUtils.pdfPath + date + ".pdf";
        //showProgressDialog(getString(R.string.create_pdf));
        io.reactivex.Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                PdfUtils.createFile(pathPdf, data, date);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.io2MainObservable()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposablePdf=d;
            }
            @Override
            public void onNext(Object o) { }
            @Override
            public void onError(Throwable e) { }
            @Override
            public void onComplete() {
                webView.loadUrl("file:///android_asset/demo.html?" + pathPdf);//pdfUrl可以是本地文件，也可以是网页链接
            }
        });

    }


    public void sharePdfByPhone(Context context, String path) {
        Uri imageUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(),
                    getString(R.string.fileprovider), new File(path));
        } else {
            imageUri = Uri.fromFile(new File(path));
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("*/*");
        context.startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
    }
    /**
     * 循环读取 文件夹下所有 eggs数据
     * List<String>
     * @param Filepath
     */
    public  static List<Integer> Fileread(String Filepath) {
        List<Integer> s = new ArrayList<>();
        File fileIN = new File(Filepath); //定义输入文件
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileIN);
            int len; //变量len用来存储每次读取数据后的返回值
            while( ( len=fis.read() ) != -1 ) {
                s.add(len);
                //  s.add(Integer.parseInt(String.valueOf(len),16));//原来为10进制，现在转为16进制
            }
            fis.close();
        } catch (IOException e)
        { e.printStackTrace(); }

        return  s;
    }

}
